package com.nju.edu.erp.service.finance;

import com.nju.edu.erp.dao.AccountDao;
import com.nju.edu.erp.exception.MyServiceException;
import com.nju.edu.erp.model.po.AccountPO;
import com.nju.edu.erp.model.vo.AccountVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountServiceImpl implements AccountService {
    private final AccountDao accountDao;
    @Autowired
    public AccountServiceImpl(AccountDao accountDao) {

        this.accountDao = accountDao;
    }

    @Override
    public void register(AccountVO accountVO) {
        AccountPO accountPOSave=new AccountPO();
        BeanUtils.copyProperties(accountVO,accountPOSave);
        accountDao.create(accountPOSave);
    }

    @Override
    @Transactional
    public List<AccountVO> queryAllAccount() {
        List<AccountPO> queryAns = accountDao.findAll();
        List<AccountVO> responseVO = queryAns.stream().map(accountPO -> {
            AccountVO accountVO = new AccountVO();
            BeanUtils.copyProperties(accountPO,accountVO);
            return  accountVO;
        }).collect(Collectors.toList());
        return responseVO;
    }

    @Override
    public void updateAccount(AccountVO accountVO) {
        AccountPO accountPOSave=new AccountPO();
        BeanUtils.copyProperties(accountVO,accountPOSave);
        accountDao.update(accountPOSave);
    }
    @Override
    public void delete(int id) {
        int ans = accountDao.delete(id);
        if (ans == 0) {
            throw new MyServiceException("B0004", "删除失败！");
        }

    }
    @Override
    public AccountPO findAccountByName(String name) {
        return accountDao.findOneByName(name);
    }
}
